var express = require('express');
var router = express.Router();
const path = require('path');
const fs = require('fs');
const svg = require('svg-captcha');
const time = require('time-stamp');
const session = require('cookie-session')

// /* GET home page. */
// 打开注册页
router.get('/register', function (req, res) {
  res.render('register');
});



// 验证码
router.get('/code', (req, res) => {
  let captcha = svg.create({
    size: 4,
    ignoreChars: 'oOiI1lL',
    color: true,
    noise: 3,
    background: '#ccc'
  })
  req.session.yzm = captcha.text;
  console.log(captcha.text);
  res.type('svg');
  res.send(captcha.data);

})
// 判断
router.post('/register', (req, res, next) => {
  let { tel, pass, pass2, yzm } = req.body;
  console.log(tel, pass, pass2, yzm);
  // 获取persons.json数据
  let dir = path.join(__dirname, '../persons.json');
  let data = fs.readFileSync(dir, 'utf-8');
  data = JSON.parse(data);
  // 传参不能为空
  if (!tel || !pass || !pass2) {
    next('请输入有效内容');
    return;
  }
  // 判断两次密码是否一致
  if (pass != pass2) {
    next('两次密码输入不一致');
    return;
  }
  // 判断是否存在
  let s = data.find(item => item.username == tel);
  if (s) {
    next('用户名已存在');
    return;
  }
  // 验证码
  console.log(req.session.yzm);
  if (!yzm) {
    next('验证码为空');
    return;
  }
  if (req.session.yzm != yzm) {
    next('验证码输入有误');
    return;
  }
  // 用户名不存在可注册
  data.push({ username: tel, password: pass, time: req.time });
  fs.writeFileSync(dir, JSON.stringify(data));
  res.render('public',{end:'注册成功'})
})

module.exports = router;
